//
//  OCNative.m
//  Manager
//
//  Created by issac on 15/8/31.
//  Copyright (c) 2015年 52xiaoluo. All rights reserved.
//

#import "OCNative.h"
#import <objc/message.h>



@implementation OCNative {
    NSMutableDictionary *methods;
}

-(id) init {
    methods = [[NSMutableDictionary alloc] init];
    unsigned int numMethods = 0;
    Method * methods1 = class_copyMethodList(self.class, &numMethods);
    for (int i = 0; i < numMethods; ++i) {
        SEL selector = method_getName(methods1[i]);
        NSMethod *nsmethod = [[NSMethod alloc] init];
        nsmethod.method = methods1[i];
        NSString *methodStr = NSStringFromSelector(selector);
        NSRange range = [methodStr rangeOfString:@":"];
        NSString *subMethod = methodStr;
        if (range.location != NSNotFound) {
            subMethod = [methodStr substringToIndex:range.location];
        }
        methods[subMethod] = nsmethod;
    }
    DLog(@"methods=%@",methods);
    return self;
}

-(void)getImei:(NSArray *)args {
    if (args.count < 1) {
        DLog(@"params illegal");
        return;
    }
    JSCallback *callback = (JSCallback *)args[0];
    [callback apply:[[ [UIDevice currentDevice] identifierForVendor] UUIDString]];
}

-(void)delayJsCallback:(NSArray *)args {
    if (args.count < 4) {
        DLog(@"params illegal");
        return;
    }
    long arg1 = [(NSNumber *)args[0] longValue];
    NSString *str = args[1];
    double dou = [(NSNumber *)args[2] doubleValue];
    JSCallback *callback = (JSCallback *)args[3];
    [callback apply:@"from oc"];
}

-(void)call:(NSString *)params {
    NSError *error;
    NSData *paramData = [params dataUsingEncoding:NSUTF8StringEncoding];
    NSDictionary *json = [NSJSONSerialization JSONObjectWithData:paramData options:NSJSONReadingMutableLeaves error:&error];
    NSString *method = json[@"method"];
    NSArray *types = json[@"types"];
    NSArray *args = json[@"args"];
    DLog(@"method=%@,types=%@,args=%@",method,types,args);
    NSMutableArray *vals = [[NSMutableArray alloc] init];
    for (int i=0; i<types.count; i++) {
        NSString *type = types[i];
        if ([@"function" isEqualToString:type]) {
            NSNumber *number = args[i];
            JSCallback *jscallback = [[JSCallback alloc] initWithIndex:(int)number.longValue];
            vals[i] = jscallback;
            jscallback.webview = self.webview;
        } else {
            vals[i] = args[i];
        }
    }
    if ([@"getImei" isEqualToString:method]) {
        [self getImei:vals];
    } else if ([@"delayJsCallback" isEqualToString:method]) {
        [self delayJsCallback:vals];
    }
}
@end
